package com.example.nutritionmanager

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.camera.view.PreviewView
import androidx.navigation.NavController
import coil.compose.rememberImagePainter
import androidx.lifecycle.LifecycleOwner
import com.example.nutritionmanager.R

@Composable
fun ScanScreen(navController: NavController) {

    // Initialize Uri state for selected image
    val imageUri = remember { mutableStateOf<Uri?>(null) }
    // Activity result launcher for picking an image from the gallery
    val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        imageUri.value = uri
    }
    // Initialize context for permission checks
    val context = LocalContext.current

    // Camera permission launcher
    val cameraPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            // Permission granted, proceed to camera functionality
            Toast.makeText(context, "Camera permission granted", Toast.LENGTH_SHORT).show()
        } else {
            // Permission denied
            Toast.makeText(context, "Camera permission denied", Toast.LENGTH_SHORT).show()
        }
    }

    // Storage permission launcher (for reading from gallery)
    val storagePermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            // Permission granted, proceed to access storage
            Toast.makeText(context, "Storage permission granted", Toast.LENGTH_SHORT).show()
        } else {
            // Permission denied
            Toast.makeText(context, "Storage permission denied", Toast.LENGTH_SHORT).show()
        }
    }

    // Request permissions on first composition
    LaunchedEffect(true) {
        // Request camera permission
        cameraPermissionLauncher.launch(Manifest.permission.CAMERA)

        // Request storage permission (for Android versions that require this)
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.P) {
            storagePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    var cameraProvider: ProcessCameraProvider? by remember { mutableStateOf(null) }

    // Initialize the camera provider
    LaunchedEffect(true) {
        val provider = ProcessCameraProvider.getInstance(context).get()
        cameraProvider = provider
    }

    // Layout
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // Display Camera Preview
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
        ) {
            cameraProvider?.let {
                CameraPreview(cameraProvider = it)
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Capture Button
        Row(
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(onClick = {
                // Trigger camera capture (implement logic for camera capture)
                Toast.makeText(context, "Capture Button Clicked", Toast.LENGTH_SHORT).show()
            }) {
                Text("拍照", fontSize = 16.sp)
            }

            Spacer(modifier = Modifier.width(16.dp))

            // Choose Image from Gallery
            Button(onClick = {
                // If storage permission is granted, open gallery
                if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.P) {
                    // Open gallery on Android 11 and above
                    pickImage.launch("image/*")
                } else {
                    // If storage permission isn't granted, request it
                    storagePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
                }
            }) {
                Text("选择图片", fontSize = 16.sp)
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        imageUri.value?.let {
            // Show selected image from gallery
            Image(painter = rememberImagePainter(it), contentDescription = "选中的图片")
        }
    }
}

@Composable
fun CameraPreview(cameraProvider: ProcessCameraProvider) {
    val context = LocalContext.current

    // Set up a Preview UseCase for CameraX
    val previewUseCase = remember {
        Preview.Builder().build()
    }

    // Initialize PreviewView for camera preview
    val previewView = remember {
        PreviewView(context)
    }

    val lifecycleOwner = context as LifecycleOwner

    // Use LaunchedEffect to ensure we only bind once during the lifecycle
    LaunchedEffect(true) {
        cameraProvider.bindToLifecycle(
            lifecycleOwner,
            CameraSelector.DEFAULT_BACK_CAMERA,
            previewUseCase
        )
        previewUseCase.setSurfaceProvider(previewView.surfaceProvider)
    }

    // Render PreviewView in Composable
    AndroidView(
        factory = {
            previewView
        },
        modifier = Modifier.fillMaxSize()
    )
}
